package com.pan.insist.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pan.insist.annotation.CacheLock;
import com.pan.insist.annotation.OperateLog;
import com.pan.insist.base.BaseController;
import com.pan.insist.constant.OperateConstant;
import com.pan.insist.model.ImagesModel;
import com.pan.insist.service.ImagesService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;


/**
 * <p>
 * 图片-前端控制器
 * </p>
 *
 * @author 黄阿能
 * @since 2020-01-16
 */

@Log4j2
@Controller
@RequestMapping("/images")
public class ImagesController extends BaseController {
    @Resource
    private ImagesService imagesService;

    private final static String PREFIX = "images/";

    /**
     * 跳转到图片首页
     */
    @GetMapping("/list")
    public String list() {
        return PREFIX + LIST;
    }

    @ResponseBody
    @GetMapping("/listJson")
    @OperateLog(operateModule = "图片管理", operateType = OperateConstant.SELECT, operateDesc = "查看图片列表")
    public JSONObject listJson(Page<ImagesModel> iPage, ImagesModel imagesModel) {
        QueryWrapper<ImagesModel> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(imagesModel.getUrl())) {
            queryWrapper.lambda().like(ImagesModel::getUrl, imagesModel.getUrl());
        }
        iPage = imagesService.page(iPage, queryWrapper);
        return page2LayTablePage(iPage);
    }

    @GetMapping("/view")
    @CacheLock(prefix = "view")
    @OperateLog(operateModule = "图片管理", operateType = OperateConstant.VIEW, operateDesc = "查看图片详情")
    public String view(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("id不存在");
        }
        ImagesModel imagesModel = imagesService.getById(id);
        modelMap.put("imagesModel", imagesModel);
        return PREFIX + VIEW;
    }

    @GetMapping("update")
    @OperateLog(operateModule = "图片管理", operateType = OperateConstant.VIEW, operateDesc = "跳转图片详情")
    public String toUpdate(String id, ModelMap modelMap) {
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("请选择一条数据！");
        }

        ImagesModel imagesModel = imagesService.getById(id);
        if (imagesModel == null) {
            log.info("查询不到数据！");
            throw new RuntimeException("请选择一条数据！");
        }
        modelMap.put("imagesModel", imagesModel);
        return PREFIX + INPUT;
    }
}
